package com.teacher.hong.controller;

import com.teacher.hong.bean.Page;
import com.teacher.hong.entity.Student;
import com.teacher.hong.service.IStudentService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学生类控制器
 */
@Slf4j
@RestController
@RequestMapping("student")
public class StudentController extends BaseController {



    @Resource
    IStudentService studentService;


    @Data
    static class ListParam {
        @NotNull(message = "页码必须传递")
        private Integer pageIndex;
        @NotNull(message = "班级ID必须传递")
        private Integer clazzId;
        private String name;
    }

    /**
     * 学生列表
     * @param param
     * @return
     */
    @PostMapping
    public Object index(@Valid @RequestBody ListParam param, BindingResult result){
        Page<Student> studentPage = studentService.page(param.getPageIndex(), param.getClazzId(), param.getName());
        return success("success", studentPage);
    }

    /**
     * 新增/编辑
     * @param student
     * @return
     */
    @PostMapping("edit")
    public Object edit(@Valid @RequestBody Student student, BindingResult result){
        return studentService.save(student) ?
                success("success", null) :
                fail("fail, 未找到对应ID的学生", 600);
    }

    /**
     * 删除学生
     * @param id
     * @return
     */
    @GetMapping("delete/{id}")
    public Object delete(@PathVariable Integer id){
        return studentService.remove(id) ?
                success("success", null) :
                fail("fail, id is not exists.", 402);
    }

}
